package com.nail.api.user.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.nail.api.user.bean.Role;
import com.nail.api.user.bean.User;
import com.nail.api.user.dao.IRoleDao;
import com.nail.api.user.dao.IUserDao;
import com.nail.api.user.service.IUserService;
import com.nail.client.RedisClient;
import com.nail.common.Constant;
import com.nail.utils.PageResult;

@Service("userService")
public class UserServiceImpl implements IUserService{

	Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private IUserDao userDao;

	@Autowired
	private RedisClient redisClient;

	@Autowired
	private IRoleDao roleDao;

	@Transactional
	public Map<String,Object> LoginIn(String userName, String password){
		User user = userDao.getUserByNameAndPassword(userName,password);
		if(user == null){
			return null;
		}
		Role role = roleDao.selectByPrimaryKey(user.getRoleId());
		user.setRole(role);
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			if(user != null){
				if( user.getIsAble() == 0){
					map.put("isAble","0");
					return map;
				}
				String token = UUID.randomUUID().toString().replaceAll("-","");
				redisClient.set(Constant.REDIS_USER_KEY+token,user,30*60L);
				map.put("token",token);
				user.setPassword(null);
				map.put("user",user);
				userDao.setLastLoginTime(user.getId());
				return map;
			}
			return null;          
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.toString());
			return null;
		}
	}


	public User getUserByName(String userName){
		return userDao.getUserByName(userName);
	}

	@Transactional
	public Map<String,Object> registerUser(User user){
		try {
			User usrSelect = userDao.getUserByName(user.getUserName());

			Map<String,Object> map = new HashMap<String,Object>();

			if(usrSelect != null){
				map.put("error","user is exist!");
				return map;
			}

			User usrMobile = userDao.getUserByMobile(user.getMobile());
			
			if(usrMobile != null){
				map.put("error","mobile is exist!");
				return map;
			}
			
			user.setCreateTime(new Date());
			user.setStatus(1);
			user.setType(0);
			user.setRole(roleDao.selectByPrimaryKey(user.getRoleId()));
			int i = userDao.insertSelective(user);
			String token = UUID.randomUUID().toString().replaceAll("-","");
			redisClient.set(Constant.REDIS_USER_KEY+token,user,30*60L);
			map.put("token",token);
			user.setPassword(null);
			map.put("user",user);
			if(i > 0){
				return map;
			}else{
				return null;
			}
		} catch (Exception e){
			e.printStackTrace();
			logger.error(e.toString());
			throw new RuntimeException("用户注册失败！");
		}
	}


	public boolean getUserIsExist(String userName){
		User user = userDao.getUserByName(userName);
		if(user == null){
			return false;
		}
		return true;
	}

	public User getUserById(Long id){
		return  userDao.selectByPrimaryKey(id);
	}

	public void updateUser(User user){
		userDao.updateByPrimaryKeySelective(user);
	}

	public User getUserByUserName(String userName) {
		return  userDao.getUserByName(userName);
	}

	public PageResult getUserByCondition(PageResult pageResult,String condition) {
		Map<String, Object> map = (Map<String, Object>)JSONObject.parse(condition);
		
		StringBuffer selectSQL = new StringBuffer("select * from user where 1=1");
		StringBuffer countSQL = new StringBuffer("select count(1) from user where 1=1");
		
		if(!map.isEmpty()) {
			if(map.get("userName") != null){
				selectSQL.append(" and user_name =" + map.get("userName"));
				countSQL.append(" and user_name =" + map.get("userName"));
			}
			
			if(map.get("mail") != null){
				selectSQL.append(" and user_name =" + map.get("mail"));
				countSQL.append(" and user_name =" + map.get("mail"));
			}

		}
		
		selectSQL.append(" limit "+ pageResult.getBegin() + ","+ pageResult.getPageSize());
		
		List<User> users = userDao.selectSQL(selectSQL.toString());
		for (User user : users) {
			user.setPassword("");
		}
		
		
		Integer count = userDao.CountSQL(countSQL.toString());
		pageResult.setData(users);
		pageResult.setTotalNum(count);
		
		return pageResult;
	}
	
	public Map<String, Object> getResult(){
		Map<String, Object> map = new HashMap<>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String today ="'" + sdf.format(new Date()) + " 00:00:00'";
		Map<String, Object> moneyStatistics = userDao.getMoneyStatistics(today);
		Map<String, Object> userStatistics = userDao.getUserStatistics(today);
		if(moneyStatistics != null){
			map.putAll(moneyStatistics);
		}
		if(userStatistics != null){
			map.putAll(userStatistics);
		}
		return map;
	}
	
	//定时任务
	@Scheduled(cron="0 0/1 * * * ?")
	public void jobSelect(){
		String sql = "SELECT count(1) FROM role";
		userDao.selectSQL(sql);
		logger.debug("*********************定时查询sql***************");
	}
}
